package org.misty.practices.algorithm.hanoi.recur;

import java.util.ArrayDeque;
import java.util.Deque;

public class Tower {
    private final Deque<Integer> stack = new ArrayDeque<>();
    private final String name;

    public Tower(String name, int level) {
        if (level < 0) {
            throw new IllegalArgumentException("level: " + level);
        }
        this.name = name;
        for (int i = level; i > 0; i--) {
            stack.push(i);
        }
    }

    public Integer head() {
        return stack.peek();
    }

    public void moveHeadTo(Tower other) {
        if (this == other) {
            return;
        }
        if (this.isEmpty()) {
            throw new RuntimeException("Tower " + name + " is Empty");
        }
        if (other.isEmpty()) {
            moveHeadTo0(other);
            return;
        }
        if (other.head() <= this.head()) {
            throw new RuntimeException("Cannot move " + name + " to " + other.name);
        } else {
            moveHeadTo0(other);
        }
    }

    private void moveHeadTo0(Tower other) {
        other.stack.push(this.stack.pop());
    }

    public boolean isEmpty() {
        return stack.isEmpty();
    }

    public String getName() {
        return this.name;
    }

    public int getLevel() {
        return this.stack.size();
    }

    public static void main(String[] args) {
        var a = new Tower("a", 5);
        var b = new Tower("b", 0);
        a.moveHeadTo(b);
        System.out.println(a);
    }
}
